<?php
/**
 * Created by PhpStorm.
 * User: Peter
 * Date: 2017/5/26
 * Time: 13:45
 */

namespace App\Http\Controllers\Api;

use App\Http\Helper\BusinessHelper;
use App\Models\TestingUserRecord;
use App\Services\CommonHelper;
use League\Flysystem\Exception;
use TokenHelperService;
use AccessTokenService;
use TestingConfig;
use TestingDeveloperService;
use DeveloperTestingRelService;
use ParamConfig;
use TestingDetailService;
use App\Services\IdEncryptService;
use TestingUserEnterpriseRelFacadeService;
use App\Models\LogHelper;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use UserRecordService;
use ResultTypeService;

class StandardApiController extends Controller
{
    /**
     * 授权接口
     */
    public function auth(Request $request)
    {
        try {
            $getToken=ParamConfig::getValue("get_token_link");
            $appid=$request->input('appid');
            $appsecret=$request->input('appsecret');
            $noncestr=$request->input('noncestr');
            $timestamp=$request->input('timestamp');
            $signature=$request->input('signature');
            $access_token_link=$getToken.'appid='.$appid.'&appsecret='.$appsecret.'&noncestr='.$noncestr.'&timestamp='.$timestamp.'&signature='.$signature;
            return curlRequest($access_token_link);
        } catch (Exception $e) {
            return apiFailed();
        }

    }

    /**
     * 获取测评列表接口
     */
    public function getTestingList(Request $request)
    {
        try {
            $token=$request->input('token');
            $eid=$request->input('eid');
            $validate= $this->tokenValidate($token);
            if($validate['errcode']!=200) {
                return apiErrcode('token_invalid');
            }
            //都转换成小写形式
            // strict case
            // $eid = mb_strtolower($eid);
            $testingDeveloper= TestingDeveloperService::getByAbbreviation($eid);
            if(!$testingDeveloper){
                return apiErrcode('enterprise_id_invalid');
            }
            $unionCode=$testingDeveloper['union_code'];
            error_log('union_code====>'.$unionCode);
            $testingList= DeveloperTestingRelService::getTestingListByUnionCode($unionCode);
            if(!$testingList){
                return apiErrcode('unionCode');
            }

            $arrayTesting=[];
            foreach ($testingList as $detail){
                $testingTid=$detail['tid'];
                $testingName=TestingDetailService::getNameByTid($testingTid);
                $testingName = $testingName ? $testingName : "";
                $encodeTid= IdEncryptService::encryption("$testingTid",'encode');
                $testingLink=ParamConfig::getValue('testing_link');
                $finalLink=urldecode($testingLink.$encodeTid);
                $temp['name']=$testingName;
                $temp['url']=$finalLink;
                array_push($arrayTesting,$temp);
            }
            return apiSuccess($arrayTesting);
        }catch(Exception $e){
            return  apiError($e);
        }

    }

    /**
     * 获取单个测评的接口
     */
    public function  accessSingleTesting(Request $request){
        try{
            $errorPage=ParamConfig::getValue("error_page");
            $token=$request->input('token');
            $tid=$request->input('tid');
            $uid=$request->input('uid');
            $organId=$request->get('organ_id');
            $order_id = $request->input('order_id');
            $nutritionist_id = $request->input('nutritionist_id');
            $nickName = $request->input('nick_name');
            $secne = $request->input('scene');
            $entry = $request->input('entry');
            $organId = $organId ? $organId :"";
            if(!$uid || empty($uid)) {
                LogHelper::log(__METHOD__.'=====>uid_invalid');
                redirectToUrl($errorPage);
                die(0);
            }
            $eid=$request->input('eid');
            $validate= $this->tokenValidate($token);
            if($validate['errcode']!=200){
                LogHelper::log(__METHOD__.'=====>token_invalid');
                redirectToUrl($errorPage);
                die(0);
            }
            $tids = IdEncryptService::encryption($tid,'decode');
            if(!$tids){
                LogHelper::log(__METHOD__.'=====>tid_invalid');
                redirectToUrl($errorPage);
                die(0);
            }

            if(!$testingInfo = TestingDetailService::getById($tids[0])){
                LogHelper::log(__METHOD__.'=====>tid_invalid');
                redirectToUrl($errorPage);
                die(0);
            }


            $testingDeveloper= TestingDeveloperService::getByAbbreviation($eid);
            if(!$testingDeveloper){
                LogHelper::log(__METHOD__.'=====>enterprise_id_invalid');
                redirectToUrl($errorPage);
                die(0);
            }
            $unionCode=$testingDeveloper['union_code'];
            //添加超级模式的开发者，不需要做权限的验证
            if($testingDeveloper['enable'] < 2){
                //验证是eid是否有测评的访问权限
                $relations = DeveloperTestingRelService::getByTidUnionCode($unionCode,$tids[0]);
                if(count($relations) <= 0){
                    LogHelper::log(__METHOD__.'=====>enterprise_id_invalid');
                    redirectToUrl($errorPage);
                    die(0);
                }
            }
            $enTid = $tid;
            if($decodeData = IdEncryptService::encryption($tid, 'decode')){
                $enTid = $decodeData[0];
            }
            $fiveDimensionTidArr = json_decode(TestingConfig::getValue('five.dimension.tids'), true);
            $dimensionV2TidArr = BusinessHelper::getDimensionV2Tids();  //新版的五维测评的ID
            $dimensionZmTidArr = BusinessHelper::getDimensionZmTids();  //智美的五维测评的ID
            if (in_array($enTid, $dimensionZmTidArr)) {
                $url = TestingConfig::getValue('dimension.zm.link');
            } elseif (in_array($enTid, $dimensionV2TidArr)) {
                $url = TestingConfig::getValue('dimension.v2.link');
            } elseif (in_array($enTid, $fiveDimensionTidArr)) {
                $url = TestingConfig::getValue('five.dimension.link');
            } else {
                $url = ParamConfig::getValue('single_testing_link');
            }

            $requestUrl = $url.$tid.'/'.$uid.'?thirdpartyName='.$eid;
            if($organId){
                $requestUrl = $requestUrl.'&organ_id='.$organId;
            }
            if($order_id && $nutritionist_id){
                $requestUrl = $requestUrl.'&order_id='.$order_id.'&nutritionist_id='.$nutritionist_id;
            }
            if($secne){
                $requestUrl = $requestUrl.'&scene='.$secne;
            }
            if($nickName){
                $requestUrl = $requestUrl.'&nick_name='.$nickName;
            }
            if ($entry) {
                $requestUrl = $requestUrl . '&entry=' . $entry;
            }
            $isNewUser = false;
            $result = TestingUserEnterpriseRelFacadeService::getByUidEid($uid, $eid,$organId);

            if (!$result) {
                $data['user_id'] = $uid;
                $data['enterprice_id'] = $eid;
                $data['union_code']=$unionCode;
                if($organId){
                    $data['organ_id']=$organId;
                }
                TestingUserEnterpriseRelFacadeService::store($data);
                $isNewUser = true;
            }
            $log = [
                'time' => date('Y-m-d'),
                'param' =>[
                    'token' => $token,
                    'tid' => $tid,
                    'uid' => $uid,
                    'eid' => $eid,
                ],
                'testing_url' => $requestUrl,
                'is_new_user' => $isNewUser
            ];
            LogHelper::log($log,'standard_testing');
            redirectToUrl($requestUrl);
        }catch(Exception $e){
            return apiError($e);
        }

    }


    /**
     * Determine whether the user has done the test
     */
    public function  judgeUserRecord(Request $request){
        try{
            $token = $request->input('token');
            $tid = $request->input('tid');
            $uid = $request->input('uid');
            $eid = $request->input('eid');
            $organId = $request->input('organ_id');

            if(!($token && $uid && $eid && $organId && $tid))
            {
                return apiErrcode('param');
            }

            $tid = IdEncryptService::encryption($tid,'decode');
            if(!$tid) {
                return apiErrcode('tid_invalid');
            }
            $tid=$tid[0];
            $validate= $this->tokenValidate($token);
            if($validate['errcode']!=200){
                return apiErrcode('token_invalid');
            }

            $result1=TestingUserEnterpriseRelFacadeService::getByUidEid($uid,$eid,$organId);
            $result2=UserRecordService::getByUidTidEid($uid,$tid,$eid);
            if ($result1 && $result2)
            {
                return apiSuccess('true');
            }
            return apiFailed();
        }catch(Exception $e){
            return apiError($e);
        }
    }



    /**
     * 验证token接口方法，调用的是sp.qiezilfie.com上的
     */
    public function  tokenValidate($token){
        $tokenValidateLink=ParamConfig::getValue('test_validate_token_link');
        $tokenValidateLink=$tokenValidateLink.$token;
        error_log("token valid url==============>".$tokenValidateLink);
        return json_decode(curlRequest($tokenValidateLink),true);
    }

    /**
     * 获取用户答题记录的分析数据
     */
    public function getUserTestingRecordListAnylasis(Request $request){
        try{
            $token=$request->input('token');
            $eid=$request->input('eid');
            $validate= $this->tokenValidate($token);
            if($validate['errcode']!=200) {
                return apiErrcode('token_invalid');
            }
            // strict case
            // $eid = mb_strtolower($eid);
            $testingDeveloper= TestingDeveloperService::getByAbbreviation($eid);
            if(!$testingDeveloper){
                return apiErrcode('enterprise_id_invalid');
            }

            $tid=$request->input('tid');
            $tids = IdEncryptService::encryption($tid,'decode');
            if(!$tids){
                return apiErrcode('tid_invalid');
            }

            if(!$testingInfo = TestingDetailService::getById($tids[0])){
                return apiErrcode('tid_invalid');
            }
            $page = $request->input('page');
            //根据用户编号和企业编号获取用户的答题记录
            $list = UserRecordService::getListByTidWithPage($tids[0],$eid,$page);
            if(count($list) > 0){
                foreach ($list as $key => &$val){
                    $recordId = $val['rid'];
                    $val['rid'] = IdEncryptService::encryption($recordId,'encode');
                    //等正式需求之后正式使用，先返回答案串
//                    $analysisData = ResultTypeService::getUserAttributeByRecordId($recordId);
//                    $val['answers'] = $analysisData['answers'];
//                    $val['attributes'] = $analysisData['attributes'];
                    unset($val['tid']);
                }
            }
            return apiSuccess($list);
        }catch (Exception $e){
            return apiError();
        }
    }

    /**
     * 数字的加密接口
     */
    public function encodeNumber(Request $request){
        $number = $request->input('number');
        if(!is_numeric($number)){
            return apiFailed(null,'number is invalid');
        }
        $encode = IdEncryptService::encryption($number,'encode');
        return apiSuccess($encode);

    }

    /**
     * 用户最新的答题记录api接口
     */
    public function  getUserRecord(Request $request){
        try{
            $token = $request->input('token');
            $tid = $request->input('tid');
            $uid = $request->input('uid');
            $eid = $request->input('eid');
            if(!$uid) {
                return apiErrcode('uid_invalid');
            }

            //兼容我们自己平台uid情况
            $uidDecode = IdEncryptService::encryption($uid,'decode');
            if($uidDecode){
                $uid = $uidDecode[0];
            }


            $validate= $this->tokenValidate($token);
            if($validate['errcode']!=200){
                return apiErrcode('token_invalid');
            }

            $tids = IdEncryptService::encryption($tid,'decode');
            if(!$tids) {
                return apiErrcode('tid_invalid');
            }

            if(!$testingInfo = TestingDetailService::getById($tids[0])){
                return apiErrcode('tid_invalid');
            }

            if(!$developer = TestingDeveloperService::getByAbbreviation($eid)){
                return apiErrcode('enterprise_id_invalid');
            }

            //验证是eid是否有测评的访问权限
            $relations = DeveloperTestingRelService::getByTidUnionCode($developer['union_code'],$tids[0]);
            if(count($relations) <= 0){
                return apiErrcode('eid_tid_not_match');
            }

            $result = TestingDetailService::getTestingResultByUidTid($uid,$tids[0]);
            return apiSuccess($result);
        }catch(Exception $e){
            return apiError($e);
        }
    }

    /**
     * @deprecated
    */
    public function getAnswerByRecordId(Request $request){
        $recordId = $request->input('recordId');
        $record = UserRecordService::getById($recordId);
        $answers = ResultTypeService::getUserAnswerByRecord($record);
        return apiSuccess($answers);
    }


    /**
     * 获取用户答案接口
     */
    public function getTestingAnswer(Request $request){
        $token=$request->input('token');
        $validate= $this->tokenValidate($token);
        if($validate['errcode']!=200) {
            return apiErrcode('token_invalid');
        }

        //验证eid
        $eid=$request->input('eid');
        // strict upper or lower case
        // $eid = mb_strtolower($eid);
        $testingDeveloper= TestingDeveloperService::getByAbbreviation($eid);
        if(!$testingDeveloper){
            return apiErrcode('enterprise_id_invalid');
        }
        //验证记录id
        $recordIdEncode = $request->input('recordId');
        $recordIdDecode = IdEncryptService::encryption($recordIdEncode,'decode');
        if(!$recordIdDecode){
            return apiErrcode('user_record_id_invalid');
        }
        $recordId = $recordIdDecode[0];

        //用户日志记录
        $userRecord = UserRecordService::getById($recordId);
        $fromPartner = $userRecord['from_partner'];
        if($fromPartner != $eid){
            return apiErrcode('record_enterprise_not_match');
        }

        $tid = $userRecord['tid'];
        $testingDetail = TestingDetailService::getItem($tid);
        $items = $testingDetail['questionList'];
        $answerStr = $userRecord['answers'];
        $answers = CommonHelper::convertAnswerToObj($answerStr);
        $indexes = array_keys($answers);
        $list = [];
        foreach ($items as $item){
            $index = $item['index'];
            if(in_array($index,$indexes)){
                $obj['index'] = $index;
                $obj['question'] = $item['title'];
                $obj['answer'] = $answers[$index]['answer'];
                array_push($list,$obj);
            }
        }
        return apiSuccess($list);
    }
}